<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"
      crossorigin="anonymous"
    />
    <style>
      form {
        width: 500px;
        margin: 50px auto;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <form>
        <div class="form-group">
          <label for="username">用户名</label>
          <input type="text" class="form-control" id="username" />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input type="password" class="form-control" id="password" />
        </div>
        <button class="btn btn-primary">登录</button>
      </form>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/jsencrypt/3.0.0-beta.1/jsencrypt.min.js"></script>
    <script>
      let publicKey = "";
      const ajax = (url, method = "GET", data = {}) => {
        return new Promise((resolve) => {
          $.ajax({
            url: "http://localhost:3000/api" + url,
            method,
            data: { ...data },
            dataType: "json",
            success(res) {
              resolve(res);
            },
          });
        });
      };

      window.onload = async () => {
        const res = await ajax("/users/key");
        // console.log(res);
        publicKey = res.publicKey;
      };

      $(".btn-primary").on("click", async (e) => {
        e.preventDefault();

        let encrypt = new JSEncrypt();
        encrypt.setPublicKey(publicKey);

        const userInfo = JSON.stringify({
          username: $("#username").val(),
          password: $("#password").val(),
        }); //需要加密的账号密码
        const encryptKey = encrypt.encrypt(userInfo); //使用公钥加密，得到密文
        // console.log(encryptKey);

        const res = await ajax("/users/login", "POST", {
          info: encryptKey,
        });
        if (res.status === 0) {
          localStorage.setItem("token", res.token);
          location.href = "./index.html";
          // alert(res.msg);
          // console.log(res);
        } else {
          alert(res.msg);
        }
      });
    </script>
  </body>
</html>
